/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ventanita.java
 *
 * Created on 04-dic-2011, 17:37:50
 */
package gui;
import SQL.Conexion;
import controlador.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import modelo.*;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author german
 */
public class ventanita extends javax.swing.JFrame {
    
        private BufferedImage image = null;
        FileInputStream fip=null;
        

    /** Creates new form ventanita */
    public ventanita() {
        initComponents();
    }
     // coloca esta en el objeto BufferedImage, o sea en memoria
    public void cargar_imagen_en_buffer(URL _url)
    {
        //se llena el buffer con la imagen        
            try 
            {
                image = ImageIO.read(_url);
                
            } catch (Exception ex) {
                System.out.println("problema --"+ex);
            }
    }
    public BufferedImage Obtener_imagen_de_Buffer()
    {       
        return image;
    }

    /* Metod que muestra una ventana de dialgo para aÃ±adir "archivo de imagen"
    *  en memoria  */


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        PanelImagen = new javax.swing.JPanel();
        brnSubir = new javax.swing.JButton();
        btnEnviar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        PonerImagen = new javax.swing.JButton();
        labelImg = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout PanelImagenLayout = new javax.swing.GroupLayout(PanelImagen);
        PanelImagen.setLayout(PanelImagenLayout);
        PanelImagenLayout.setHorizontalGroup(
            PanelImagenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 272, Short.MAX_VALUE)
        );
        PanelImagenLayout.setVerticalGroup(
            PanelImagenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 344, Short.MAX_VALUE)
        );

        brnSubir.setText("Subir Imagen");
        brnSubir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                brnSubirActionPerformed(evt);
            }
        });

        btnEnviar.setText("Enviar Imagen");
        btnEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnviarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(59, 59, 59)
                        .addComponent(PanelImagen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(brnSubir)
                        .addGap(64, 64, 64)
                        .addComponent(btnEnviar)))
                .addContainerGap(124, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PanelImagen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(brnSubir)
                    .addComponent(btnEnviar))
                .addGap(46, 46, 46))
        );

        jTabbedPane1.addTab("tab1", jPanel1);

        PonerImagen.setText("POnerImagen");
        PonerImagen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PonerImagenActionPerformed(evt);
            }
        });

        labelImg.setText("jLabel1");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(153, 153, 153)
                        .addComponent(PonerImagen))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(88, 88, 88)
                        .addComponent(labelImg, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(134, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(75, 75, 75)
                .addComponent(labelImg, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 118, Short.MAX_VALUE)
                .addComponent(PonerImagen)
                .addGap(20, 20, 20))
        );

        jTabbedPane1.addTab("tab2", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnviarActionPerformed
// TODO add your handling code here:
    Connection conexion = Conexion.getConexion();
        try {
            PreparedStatement st = conexion.prepareStatement("insert into testImagen(nombre, imagen) values('yeah',?)");
            st.setBlob(1, fip);
            st.execute();
            st.close();
        } catch (SQLException ex) {
            Logger.getLogger(ventanita.class.getName()).log(Level.SEVERE, null, ex);
        }
    
}//GEN-LAST:event_btnEnviarActionPerformed

private void brnSubirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_brnSubirActionPerformed
// TODO add your handling code here:
//Valor que tomara el fileChooser
    JFileChooser ven = new JFileChooser();
//Añadiendole un filtro
    FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & PNG", "jpg", "png");
    ven.setFileFilter(filter);
    int result = ven.showOpenDialog(null);
       if ( result == JFileChooser.APPROVE_OPTION )
       {
            try 
            {
                //se asigna a "url" el archivo de imagen seleccionado
                URL url = ven.getSelectedFile().toURL();
                cargar_imagen_en_buffer(url);
                this.PanelImagen.add(new panelImagen(Obtener_imagen_de_Buffer(), PanelImagen.getSize()));
                PanelImagen.setVisible(true);
                PanelImagen.repaint();
                fip= new FileInputStream(ven.getSelectedFile());
 
             }
            catch (Exception ex) {
                System.out.println("problema --"+ex);
            }
       }
    
    
    
}//GEN-LAST:event_brnSubirActionPerformed

public Image abrirImagen() throws SQLException, IOException
 {
 Image rpta=null;
 String sql ="select imagen from testImagen where nombre='yeah'";
  Connection conexion = Conexion.getConexion();
 //En este ejemplo solo recupero la primera Imagen
 
 java.sql.Statement stmt = conexion.createStatement();
 ResultSet results = stmt.executeQuery(sql);
 Blob imagen=null;
 while(results.next())
 {
    imagen = results.getBlob("imagen");
 }

 rpta= javax.imageio.ImageIO.read(imagen.getBinaryStream());
 //Esta parte es clave, donde se convierte a imagen
  return rpta;
}

private void PonerImagenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PonerImagenActionPerformed
        try {
            // TODO add your handling code here:
                 ImageIcon  img = new ImageIcon (abrirImagen());
                 this.labelImg.setIcon(img);
        } catch (SQLException ex) {
            Logger.getLogger(ventanita.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ventanita.class.getName()).log(Level.SEVERE, null, ex);
        }
     
     
     
     
    
    
}//GEN-LAST:event_PonerImagenActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ventanita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ventanita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ventanita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ventanita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ventanita().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PanelImagen;
    private javax.swing.JButton PonerImagen;
    private javax.swing.JButton brnSubir;
    private javax.swing.JButton btnEnviar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel labelImg;
    // End of variables declaration//GEN-END:variables
}
